/* 埋点内容 */
import timeFormat from '@/uview-ui/libs/function/timeFormat'
import request from '@/utils/request.js'
import schemeMap from '@/static/scheme'
import { getUserInfo } from './user'

/* 路由监听 */
let lastRoute = { // 上一个页面路由
  scheme: 'Entry', // 默认是从entry进入
  enterTime: timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
  leaveTime: timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
}

let currentRoute = { // 当前页面路由
  scheme: '',
  enterTime: timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
  leaveTime: timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
}

function setCurrentRoute(res) {
  /* 记录上一个路由，离开时间重新更新 */
  lastRoute = currentRoute
  lastRoute.leaveTime = timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')

  /* 记录当前路由 */
  const currentPath = '/' + res.path

  /* 查找scheme */
  let currentScheme = ''

  for (const key in schemeMap) {
    if (schemeMap[ key ].path === currentPath) {
      currentScheme = key
      break
    }
  }
  if (currentScheme === '') {
    console.error('当前页面为设置scheme!!')
  }
  currentRoute = {
    scheme: currentScheme,
    enterTime: timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
    leaveTime: timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
  }
  console.log('路由切换', lastRoute, currentRoute)
}

/* 路由变化监听 */
wx.onAppRoute(res => {
  setCurrentRoute(res)
})

/**
 * 设置页面停留/离开时间相关数据
 */
const eventStoreApi = (eventId, data = {}) => request('/event/eventTrigger/eventStore', 'POST', {
  eventId,
  time: timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
  userId: getUserInfo() && getUserInfo().userInfo ? getUserInfo().userInfo.userId : '',
  data
})

/**
 * 停留埋点。ns后执行埋点数据
 */
export function eventStoreStay(time) {
  return setTimeout(() => {
    eventStoreApi(4, {
      pageScheme: currentRoute.scheme,
      timeCount: time,
    })
    console.log('停留埋点', lastRoute, currentRoute)
  }, time * 1000)
}

/**
 * 离开埋点，记录停留时间
 */
export function eventStoreLeave() {
  setTimeout(() => {
    const time = new Date(lastRoute.leaveTime).getTime() - new Date(lastRoute.enterTime).getTime()

    eventStoreApi(5, {
      stayTime: time,
      leavePageScheme: lastRoute.scheme,
      enterPageScheme: currentRoute.scheme
    })
    console.log('离开埋点', `${ time / 1000 }s`)
  })
}

/**
 * 搜索关键词埋点
 */
export function eventStoreSearchKey(key) {
  eventStoreApi(7, {
    searchKey: key
  })
  console.log('搜索埋点', key)
}

/**
 * 项目访问记录埋点, 设置5s延时，防止反复进入
 */
export function eventStoreProject(projectId) {
  return setTimeout(() => {
    eventStoreApi(6, {
      projectId
    })
    console.log('项目访问记录埋点', projectId)
  }, 5000)
}
